from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from datetime import datetime

from module_admin.entity.do.user_do import SysUser
from module_admin.entity.do.dept_do import SysDept
from module_admin.entity.vo.user_info_vo import UserInfoResponse
from exceptions.exception import ServiceException
from module_vip.dao.bg_vip_dao import BgVipDao


class UserInfoService:
    """
    用户信息服务层
    """

    @classmethod
    async def get_user_info(cls, query_db: AsyncSession, user_id: int):
        """
        获取用户信息
        """
        # 查询用户基本信息
        result = await query_db.execute(
            select(SysUser, SysDept)
            .where(SysUser.user_id == user_id, SysUser.del_flag == '0')
            .join(
                SysDept,
                SysUser.dept_id == SysDept.dept_id,
                isouter=True
            )
        )
        user_data = result.first()
        
        if not user_data:
            raise ServiceException(message="用户不存在")
        
        user = user_data[0]
        dept = user_data[1]

        vip_status = '0'
        vip_expire_time = None
        # 检查VIP状态（这里可以根据实际业务逻辑来实现）
        user_vip = await BgVipDao.get_by_user_id(query_db, user_id)
        if user_vip:
            vip_status = user_vip.status
            vip_expire_time = user_vip.end_date.strftime('%Y-%m-%d %H:%M:%S')
        
        # 构建用户信息响应
        user_info = UserInfoResponse(
            user_id=user.user_id,
            user_name=user.user_name,
            nick_name=user.nick_name or user.user_name,
            email=user.email or '',
            phone=user.phonenumber,
            avatar=user.avatar,
            status=user.status,
            vip_status=vip_status,
            vip_expire_time=vip_expire_time,
            create_time=user.create_time.strftime('%Y-%m-%d %H:%M:%S') if user.create_time else ''
        )
        
        return user_info
